package com.nnnu.wsnackshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nnnu.wsnackshop.pojo.entity.Promotions;
import com.nnnu.wsnackshop.mapper.PromotionsMapper;
import com.nnnu.wsnackshop.service.IPromotionsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 促销活动 服务实现类
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PromotionsServiceImpl extends ServiceImpl<PromotionsMapper, Promotions> implements IPromotionsService {

    private final ObjectMapper objectMapper;

    @Override
    public List<Promotions> getActivePromotionsForProduct(Integer productId, Integer categoryId) {
        LocalDateTime now = LocalDateTime.now();

        LambdaQueryWrapper<Promotions> qw = Wrappers.<Promotions>lambdaQuery()
                .le(Promotions::getStartAt, now)
                .ge(Promotions::getEndAt, now);

        List<Promotions> activePromotions = baseMapper.selectList(qw);

        if (activePromotions.isEmpty()) {
            return Collections.emptyList();
        }

        // 根据 details 内容筛选适用活动
        return activePromotions.stream()
                .filter(p -> {
                    try {
                        if (p.getDetails() == null || p.getDetails().isEmpty()) {
                            return false;
                        }
                        JsonNode detailsNode = objectMapper.readTree(p.getDetails());
                        // 检查是否全局适用或与当前商品/分类匹配
                        boolean appliesToProduct = detailsNode.has("productId")
                                && detailsNode.get("productId").asInt() == productId;
                        boolean appliesToCategory = detailsNode.has("categoryId")
                                && detailsNode.get("categoryId").asInt() == categoryId;
                        boolean appliesToAll = detailsNode.has("applyToAll")
                                && detailsNode.get("applyToAll").asBoolean();

                        return appliesToAll || appliesToProduct || appliesToCategory;
                    } catch (Exception e) {
                        log.warn("解析促销活动详情失败: {}", p.getDetails(), e);
                        return false; // 解析失败则认为不适用
                    }
                })
                .collect(Collectors.toList());
    }
}
